home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 November: Tool Chest / Dev.CD Nov 00 TC Disk 2.toast / pc / sample code / quicktime / quicktimeintro / desktop sprites / start code / imagecompressionutilities.c < prev    next >
Encoding:
Text File  |  2000-10-06  |  24.0 KB  |  813 lines

  1. //////////
  2. //
  3. //    File:        ImageCompressionUtilities.c
  4. //
  5. //    Contains:    Image Compression Utilities.
  6. //
  7. //    Written by:    Peter Hoddie, Sean Allen, Chris Flick
  8. //    Revised by:    Tim Monroe
  9. //
  10. //    Copyright:    © 1998 by Apple Computer, Inc., all rights reserved.
  11. //
  12. //    Change History (most recent first):
  13. //
  14. //       <4>         12/16/98    rtm        removed orphaned prototype for compressTransparentRLEwithHitTesting
  15. //       <3>         05/28/98    rtm        added some typecasting to minimize MSDev compiler warnings
  16. //       <2>         03/22/98    rtm        made changes to RecompressPictureFileWithTransparency, as per Chris' fixes
  17. //       <1>         03/27/98    rtm        existing file
  18. //
  19. //////////
  20.  
  21.  
  22. #ifndef __CONDITIONALMACROS__
  23. #include "ConditionalMacros.h"
  24. #endif
  25.  
  26. #ifndef __COLORPICKER__
  27. #include <ColorPicker.h>
  28. #endif
  29.  
  30. #ifndef __RESOURCES__
  31. #include <Resources.h>
  32. #endif
  33.  
  34. #ifndef __ENDIAN__
  35. #include <Endian.h>
  36. #endif
  37.  
  38. #ifndef _IMAGECOMPRESSIONUTILITIES_
  39. #include "ImageCompressionUtilities.h"
  40. #endif
  41.  
  42. #ifndef __QUICKDRAW__
  43. #include "QuickDraw.h"
  44. #endif
  45.  
  46. pascal void extractStdPix( PixMap *src, Rect *srcRect, MatrixRecord *matrix, short mode, RgnHandle mask, PixMap *matte, Rect *matteRect, short flags );
  47. static ImageDescriptionHandle createImageDescription( CodecType cType, PixMapHandle pixmap );
  48. static void DrawPictureNoDither(PicHandle pic, const Rect *bounds);
  49. static OSErr prepareFor16BitCompress(PicHandle *pic);
  50.  
  51. // We use the Animation compressor at 16 bit depth in these utilities
  52. #define kCompressDepth    16
  53.  
  54. // Used for compressing QuickDraw pictures with transparency/hittesting
  55.  
  56. typedef struct {
  57.     PicHandle    picture;
  58. } PictureCompressProcData;
  59.  
  60. static pascal OSErr myPictureCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType portType, void * refcon );
  61.  
  62.  
  63. // Used for recompressing QuickTime compressed data with transparency/hittesting
  64.  
  65. typedef struct {
  66.     ImageDescriptionHandle    imageDesc;
  67.     Handle                    imageData;
  68. } CompressedImageCompressProcData;
  69.  
  70.  
  71. static pascal OSErr myImageCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType portType, void * refcon );
  72.  
  73.  
  74. // A few macros to help with error handling
  75. #define        BailIf(a, e)         {if (a)     { err = e; goto bail; }}
  76. #define        BailOSErr(a)         {if ((err = a) != noErr)    goto bail;}
  77. #define        BailMemErr(a)        {a; if ((err = MemError()) != noErr) goto bail;}
  78.  
  79.  
  80. // PICT to compressed image conversion
  81.  
  82. //    Given a QuickDraw picture, extract QuickTime compressed image data and description, if any.
  83. //
  84. //    It does this by creating a temporary CGrafPort, installing a QuickDraw bottleneck
  85. //    routine for the StdPix call, and then drawing the picture. Since this routine will
  86. //    be called whenever QuickTime compressed image data is encountered, it can
  87. //    stash away any found compressed data and description. On DrawPicture's return, the
  88. //    stashed data and description is retrieved and returned to the caller.
  89. //
  90. //    Worth noting in this utility is definition of the extractPictRecord. This is a 
  91. //    structure consisting of a CGrafPort structure followed by fields for a handle to 
  92. //    image data and an ImageDescription. This layout allows ExtractCompressData to open
  93. //    a CGrafPort using the embedded CGrafPort field, and set this as the current port. 
  94. //    Then, in the StdPix routine extractStdPix, the current port can be retrieved and 
  95. //    cast to a pointer to an extractPictRecord to get access to the other fields.
  96. //
  97.  
  98. typedef struct {
  99.     CGrafPtr tempPort;
  100.  
  101.     Handle data;
  102.     ImageDescriptionHandle idh;
  103. } extractPictRecord;
  104.  
  105.  
  106. OSErr ExtractCompressData( PicHandle thePict, Handle *dataOut, ImageDescriptionHandle *idh )
  107. {
  108.     OSErr                err = noErr;
  109.     extractPictRecord     state;
  110.     CQDProcs             procs;
  111.     GrafPtr             savePort;
  112.     Rect                 bounds;
  113.  
  114.     if ( dataOut )
  115.         *dataOut = nil;
  116.     if ( idh )
  117.         *idh = nil;
  118.  
  119.     GetPort( &savePort );
  120.     state.tempPort = CreateNewPort();
  121.     SetStdCProcs( &procs );
  122.     procs.newProc1 = (UniversalProcPtr)/*NewStdPixProc*/NewStdPixUPP(extractStdPix);
  123.     SetPortGrafProcs(state.tempPort, &procs);
  124.  
  125.     state.data = nil;
  126.     state.idh = nil;
  127.  
  128.     MacSetPort( state.tempPort );
  129.     HidePen();
  130.  
  131.     bounds = (**thePict).picFrame;
  132.     DrawPicture(thePict, &bounds);    
  133.  
  134.     MacSetPort( savePort );
  135.     DisposePort(state.tempPort);
  136.     DisposeStdPixUPP((StdPixUPP)procs.newProc1);
  137.     
  138.     *dataOut    = state.data;
  139.     *idh        = state.idh;
  140.  
  141.     return err;
  142. }
  143.  
  144.  
  145. pascal void extractStdPix( PixMap *src, Rect *srcRect, MatrixRecord *matrix, short mode, RgnHandle mask, PixMap *matte, Rect *matteRect, short flags )
  146. {
  147. #if TARGET_OS_MAC
  148. #pragma unused(srcRect,matrix,mode,mask,matte,matteRect,flags)
  149. #endif
  150.     extractPictRecord    *state;
  151.  
  152.     GetPort( (GrafPtr *)&state );
  153.  
  154.     if  ( state->idh == nil ) {
  155.         ImageDescriptionHandle    desc;
  156.         Ptr                     data;
  157.         long                    bufferSize;
  158.         OSErr                     err;
  159.         if ( (err=GetCompressedPixMapInfo(src, &desc, &data, &bufferSize, nil, nil)) == noErr ) {
  160.             state->idh = desc;
  161.             HandToHand( (Handle *)&state->idh );
  162.             PtrToHand( data, &state->data, bufferSize );
  163.         }
  164.     }
  165. }
  166.  
  167.  
  168. static ImageDescriptionHandle createImageDescription( CodecType cType, PixMapHandle pixmap )
  169. {
  170.     ImageDescriptionHandle    desc = nil;
  171.     
  172.     if ( ( desc = (ImageDescription **)NewHandleClear(sizeof(ImageDescription)) ) != nil ) {
  173.         ImageDescription     *dp = *desc;
  174.         Rect                bounds = (**pixmap).bounds;
  175.  
  176.         dp->idSize             = sizeof(ImageDescription);
  177.         dp->cType             = cType;    
  178.         dp->spatialQuality     = codecNormalQuality;
  179.         dp->width            = bounds.right - bounds.left;
  180.         dp->height             = bounds.bottom - bounds.top;
  181.         dp->hRes             = 72L << 16;
  182.         dp->vRes             = 72L << 16;
  183.         dp->dataSize         = ((**pixmap).rowBytes & 0x3fff) * dp->height;
  184.         dp->depth             = (**pixmap).pixelSize;
  185.         dp->clutID             = -1;
  186.         
  187.         if ( SetImageDescriptionCTable( desc, (**pixmap).pmTable ) ) {
  188.             DisposeHandle( (Handle) desc );
  189.             desc = nil;
  190.         }
  191.     }
  192.     return desc;
  193. }
  194.  
  195. pascal void noDitherBitsProc(BitMap *srcBits, Rect *srcRect, Rect *dstRect, short mode, RgnHandle maskRgn);
  196. pascal void noDitherBitsProc(BitMap *srcBits, Rect *srcRect, Rect *dstRect, short mode, RgnHandle maskRgn)
  197. {
  198.     mode &= ~ditherCopy;
  199.     StdBits(srcBits, srcRect, dstRect, mode, maskRgn);
  200. }
  201.  
  202. //    DrawPictureNoDither is used to draw a QuickDraw picture but to turn convert any
  203. //    use of ditherCopy graphics modes to graphics modes that don't use ditherCopy. It
  204. //    only performs this with the stdbits bottleneck routine. Since ditherCopy is simply
  205. //    ORed in with other graphics modes, the replaced bottleneck routine only needs to
  206. //    AND off the ditherCopy flag.
  207. void DrawPictureNoDither(PicHandle pic, const Rect *bounds)
  208. {        
  209.     CQDProcs procs;
  210.     GrafPtr savePort;
  211.     CQDProcsPtr saveProcs;
  212.  
  213.     GetPort(&savePort);
  214.     saveProcs = GetPortGrafProcs(savePort);
  215.     SetStdCProcs( &procs );
  216.  
  217.     procs.bitsProc = (QDBitsUPP)NewQDBitsProc(noDitherBitsProc);
  218.     SetPortGrafProcs(savePort, &procs);
  219.  
  220.     DrawPicture(pic, bounds);
  221.  
  222.     SetPortGrafProcs(savePort, saveProcs);
  223.  
  224.     DisposeQDBitsUPP((QDBitsUPP)procs.bitsProc);
  225. }
  226.  
  227.  
  228. //
  229. // The following is a routine that can be used to clean up the colors in a picture
  230. // before being compressed with the Animation compressor in 16-bits at codecNormal
  231. // quality. The QuickTime Animation compressor can operate in both a lossless and
  232. // lossy manner. This routine is meant to help when compressing in a lossy manner.
  233. //
  234. // By clean up, what's meant is the forcing of any colors that are sufficiently close
  235. // to white to colors that are not as close. Since the Animation compressor will
  236. // perform threshholding of the image's colors when codecNormal quality is specified,
  237. // without this preprocessing, colors very close to white can be mapped to white
  238. // in the compression. If white was chosen as the key color, pixels that are
  239. // close to white could possibly become transparent as well.
  240. //
  241. // While not used by other routines in this file, prepareFor16BitCompress is provided
  242. // as an example of how this might be done.
  243. //
  244. // Note that with codecLossless quality, there is no remapping of colors so this
  245. // step is unnecessary.
  246. //
  247.  
  248. #define kThreshold (255 - 16)
  249.  
  250. OSErr prepareFor16BitCompress(PicHandle *pic)
  251. {
  252.     OSErr err = noErr;
  253.     PicHandle newPicture = nil;
  254.     Rect r;
  255.     GWorldPtr gw = nil;
  256.     CGrafPtr savePort;
  257.     GDHandle saveGD;
  258.     short rowBytes;
  259.     Ptr baseAddr;
  260.     long w, h;
  261.     PixMapHandle pm;
  262.  
  263.     GetGWorld(&savePort, &saveGD);
  264.  
  265.     r = (***pic).picFrame;
  266.     MacOffsetRect(&r, (short)-r.left, (short)-r.top);
  267.  
  268.     err = NewGWorld(&gw, 32, &r, nil, nil, useTempMem);
  269.     if (err) {
  270.         err = NewGWorld(&gw, 32, &r, nil, nil, 0);
  271.         if (err) goto bail;
  272.     }
  273.  
  274.     pm = GetGWorldPixMap(gw);
  275.     LockPixels(pm);
  276.     SetGWorld(gw, nil);
  277.     EraseRect(&r);
  278.  
  279.     DrawPicture(*pic, &r);
  280.  
  281.     baseAddr = GetPixBaseAddr(pm);
  282.     rowBytes = (**pm).rowBytes & 0x3fff;
  283.     for (h=0; h<r.bottom; h++) {
  284.         long *pixelPtr = (long *)baseAddr;
  285.  
  286.         for (w=0; w<r.right; w++, pixelPtr++) {
  287.             UInt8 r, g, b, a;
  288.             long pixel = *pixelPtr;
  289.  
  290.             if ((pixel & 0x0ffffff) == 0x00ffffff)        // pure white
  291.                 continue;
  292.  
  293.             a = (pixel >> 24) & 0x0ff;
  294.             r = (pixel >> 16) & 0x0ff;
  295.             g = (pixel >>  8) & 0x0ff;
  296.             b = (pixel >>  0) & 0x0ff;
  297.             if ((r > kThreshold) && (g > kThreshold) && (b > kThreshold)) {
  298.                 r = g = b = kThreshold;
  299.                 *pixelPtr = (a << 24) | (kThreshold << 16) | (kThreshold << 8) | (kThreshold << 0);
  300.             }
  301.         }
  302.  
  303.         baseAddr += rowBytes;
  304.     }
  305.  
  306.     newPicture = OpenPicture(&r);
  307.     CopyBits((BitMap *)&pm, (BitMap *)&pm, &r, &r, ditherCopy, nil);
  308.  
  309.     ClosePicture();
  310.     UnlockPixels(pm);
  311.  
  312. bail:
  313.     if (gw)
  314.         DisposeGWorld(gw);
  315.  
  316.     if (err == noErr) {
  317.         if (newPicture) {
  318.             KillPicture(*pic);
  319.             *pic = newPicture;
  320.         }
  321.     }
  322.  
  323.     SetGWorld(savePort, saveGD);
  324.  
  325.     return err;
  326. }
  327.  
  328.  
  329. /*
  330.     ---------------- Callback based routines for compressing with hittesting and transparency ----------------
  331.  */
  332.  
  333. /*
  334.     RecompressWithTransparencyFromProc
  335.     
  336.     This is a routine either called indirectly through RecompressCompressedImageWithTransparency, 
  337.     RecompressPictureWithTransparency, or RecompressPictureFileWithTransparency or called directly.
  338.     It takes a callback procedure which is responsible for returning the dimensions of the
  339.     area of some type of drawable entity and for actually drawing that entity.
  340.     
  341.         includeHitTesting        TRUE if hit testing data should be added to the compressed data
  342.         keyColor                A RGBColor that should be used as the transparency color. Pass nil
  343.                                 if the image doesn't have transparent portions.
  344.         hitTestRegion            A RgnHandle specifying an area that is to be used as the hit test
  345.                                 area. If you pass this, you must also set includeHitTesting to TRUE.
  346.                                 This is optional as the callback procedure can perform drawing
  347.                                 itself of the hit test area which is often suitable when both the
  348.                                 image and hit test area were painted in a drawing program.
  349.         idh                        Returned ImageDescriptionHandle for the compressed image data
  350.         imageData                Returned Handle to the compressed image data
  351.  
  352.  */
  353. OSErr RecompressWithTransparencyFromProc( CompressDrawProc drawProc, void * drawProcRefcon, 
  354.                                                     Boolean includeHitTesting,
  355.                                                     RGBColor *keyColor, 
  356.                                                     RgnHandle hitTestRegion,
  357.                                                     ImageDescriptionHandle *idh, Handle * imageData )
  358. {
  359.     OSErr                         err = noErr;
  360.     Rect                        bounds;
  361.     CGrafPtr                    savePort;
  362.     GDHandle                    saveDevice;
  363.     GWorldPtr                    gwImage = nil;        // always used
  364.     GWorldPtr                    gwPrev = nil;        // used if compressing with transparency (via keycolor)
  365.     GWorldPtr                    gwMap = nil;        // used if compressing with hittesting data
  366.     ImageDescriptionHandle        desc = nil;            // resulting image description
  367.     ImageDescriptionHandle        gwMapDesc = nil;
  368.     ImageSequence                seq = 0;            // compress sequence
  369.     ImageSequenceDataSource        mapSource = 0L;
  370.     Ptr                            data = nil;
  371.     long                         dataSize;
  372.     UInt8                         similarity;
  373.     Boolean                        includeTransparency = false;
  374.     RGBColor                    saveBackColor;
  375.         
  376.     GetGWorld( &savePort, &saveDevice );
  377.     
  378.     if( !drawProc || !idh || !imageData ){
  379.         err = paramErr;
  380.         goto bail;
  381.     }
  382.     
  383.     // tell callback that it should initialize any storage it needs
  384.     err = drawProc( kRecoProcInitMsg, nil, nil, 0, drawProcRefcon );
  385.     if(err) goto bail;
  386.     
  387.     // determine bounds to use for compression
  388.     err = drawProc( kRecoProcGetBoundsMsg, &bounds, nil, 0, drawProcRefcon );
  389.     if(err) goto bail;
  390.     
  391.     err = QTNewGWorld(&gwImage, kCompressDepth, &bounds, nil, nil, kICMTempThenAppMemory);
  392.     if(err) goto bail;
  393.  
  394.     if( keyColor ) {
  395.         includeTransparency = true;
  396.     }
  397.     
  398.     // Include hit testing? If so, we need a previous buffer and an 8-bit GWorld for the mask data
  399.     if( includeHitTesting ) {
  400.         err = QTNewGWorld(&gwPrev, kCompressDepth, &bounds, nil, nil, kICMTempThenAppMemory);
  401.         if(err) goto bail;
  402.  
  403.         err = QTNewGWorld(&gwMap, 8, &bounds, nil, nil, kICMTempThenAppMemory);
  404.         if(err) goto bail;
  405.     }
  406.     
  407.     LockPixels( GetGWorldPixMap(gwImage) );
  408.     
  409.     if( gwPrev )
  410.         LockPixels( GetGWorldPixMap(gwPrev) );
  411.     
  412.     if( gwMap )
  413.         LockPixels( GetGWorldPixMap(gwMap) );
  414.     
  415.     if(gwPrev) {
  416.         SetGWorld( gwPrev, nil );
  417.         ClipRect( &bounds );
  418.         
  419.         GetBackColor( &saveBackColor );
  420.         if( keyColor )
  421.             RGBBackColor( keyColor );
  422.         
  423.             EraseRect( &bounds );
  424.             
  425.         RGBBackColor( &saveBackColor );
  426.     }
  427.     
  428.     if( gwMap ) {
  429.         SetGWorld( gwMap, nil );
  430.         
  431.         EraseRect( &bounds );            // paint background white
  432.  
  433.         err = drawProc( kRecoProcDrawMsg, &bounds, gwMap, kRecoProcHitTestingImageType, drawProcRefcon );
  434.         if(err) goto bail;
  435.         
  436.         if( hitTestRegion ) {
  437.             RGBColor blackRGB;
  438.             
  439.             blackRGB.red = blackRGB.green = blackRGB.blue = 0;
  440.             
  441.             RGBForeColor( &blackRGB );
  442.             MacPaintRgn( hitTestRegion );
  443.         }
  444.  
  445.         gwMapDesc = createImageDescription(kRawCodecType, GetGWorldPixMap(gwMap));
  446.         err = MemError();
  447.         if(err) goto bail;
  448.     }
  449.     
  450.     SetGWorld( gwImage, nil );
  451.     ClipRect( &bounds );
  452.     EraseRect( &bounds );
  453.     
  454.     desc = (ImageDescriptionHandle) NewHandle(sizeof(ImageDescription));
  455.  
  456.  
  457.     // NOTE: We pass codecLosslessQuality so that the key color if any is matched exactly. This avoids colors within
  458.     // some threshhold different from the key color being taken as equivalent to the key color. Alternatively, we
  459.     // could perform some threshhold processing on the source image's pixels and pass codecNormalQuality.
  460.     if( includeHitTesting ) {
  461.         // Allocate a compression sequence and add source data for hittest mask
  462.         err = CompressSequenceBegin(&seq, GetGWorldPixMap(gwPrev), nil, nil, nil, kCompressDepth, kAnimationCodecType, 
  463.                                             anyCodec, codecLosslessQuality, codecLosslessQuality, 2, nil, 0, desc);
  464.  
  465.         // with hit testing, we have to add a data source to hold the mask data
  466.         err = CDSequenceNewDataSource(seq, &mapSource, kRecoProcHitTestingImageType, 1, (Handle)gwMapDesc, nil, nil);
  467.         if (err) goto bail;
  468.  
  469.         err = CDSequenceSetSourceData(mapSource, GetPixBaseAddr(GetGWorldPixMap(gwMap)), (**gwMapDesc).dataSize);
  470.         if (err) goto bail;
  471.  
  472.         // What's the maximum size the compressed data could be--including hit-test data?
  473.         err = GetCSequenceMaxCompressionSize(seq, GetGWorldPixMap(gwPrev), &dataSize);
  474.     }
  475.     else
  476.     {    // not hit-testing so we only need the image buffer
  477.         err = CompressSequenceBegin( &seq, GetGWorldPixMap(gwImage), nil, &bounds, nil, kCompressDepth, kAnimationCodecType, 0, 
  478.                                     codecLosslessQuality, codecLosslessQuality, 2, nil, 0, desc );
  479.         if(err) goto bail;
  480.         
  481.         // What's the maximum size the compressed data could be?
  482.         err = GetCSequenceMaxCompressionSize(seq, GetGWorldPixMap(gwImage), &dataSize);
  483.     }
  484.     if (err) goto bail;
  485.     
  486.  
  487.     data = NewPtr( dataSize );
  488.     if(noErr != (err = MemError())) goto bail;
  489.     
  490.     if( includeHitTesting /* with or without transparency */ ) {
  491.         // With hittesting, we use two buffers. Actually we don't have to but do so to show how it can be
  492.         // done. Also, this code was based upon some older code that did.
  493.         
  494.         
  495.         // compress the GWorld painted with the keyColor exclusively
  496.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwPrev), nil, 0, data, &dataSize, &similarity, nil );
  497.         if ( err ) goto bail;
  498.  
  499.         err = SetCSequencePrev(seq, GetGWorldPixMap(gwPrev), nil);
  500.         if (err) goto bail;
  501.  
  502.         // draw the image into the GWorld over area painted with keyColor so that if picture is transparent already
  503.         // areas it doesn't paint will be in the key color
  504.         SetGWorld( gwImage, nil );
  505.         
  506.         GetBackColor( &saveBackColor );
  507.         if( keyColor )
  508.             RGBBackColor( keyColor );
  509.             
  510.             EraseRect( &bounds );
  511.         
  512.         RGBBackColor( &saveBackColor );
  513.     
  514.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  515.         if(err) goto bail;
  516.  
  517.         // now compress the GWorld holding the image drawn on top of the keyColor
  518.         err = CompressSequenceFrame(seq, GetGWorldPixMap(gwImage), nil, 0, data, &dataSize, &similarity, nil);
  519.         if (err) goto bail;
  520.         
  521.         // At this point, data points to the image data for just the difference between the two (thus generating transparency) 
  522.         // Also, hit testing data is contained in the image data if it was specified.
  523.     }
  524.     else if( includeTransparency ) {
  525.         // For transparency case without hittesting, we get by with only using a single buffer so we special case the
  526.         // code here. This is also for clarity.
  527.     
  528.         // compress the GWorld painted with the keyColor exclusively
  529.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwImage), nil, codecFlagUpdatePrevious, data, &dataSize, &similarity, nil );
  530.         if ( err ) goto bail;
  531.  
  532.         // draw the image into the GWorld over area painted with keyColor so that if picture is transparent already
  533.         // areas it doesn't paint will be in the key color
  534.         SetGWorld( gwImage, nil );
  535.         
  536.         GetBackColor( &saveBackColor );
  537.         if( keyColor )
  538.             RGBBackColor( keyColor );
  539.             
  540.             EraseRect( &bounds );
  541.         
  542.         RGBBackColor( &saveBackColor );
  543.     
  544.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  545.         if(err) goto bail;
  546.  
  547.         // now compress the GWorld holding the image drawn on top of the keyColor
  548.         err = CompressSequenceFrame(seq, GetGWorldPixMap(gwImage), nil, codecFlagUpdatePrevious, data, &dataSize, &similarity, nil);
  549.         if (err) goto bail;
  550.         
  551.         // At this point, data points to the image data for just the difference between the two (thus generating transparency) 
  552.         // Also, hit testing data is contained in the image data if it was specified.
  553.     }
  554.     else
  555.     {
  556.         SetGWorld( gwImage, nil );
  557.  
  558.         // draw the image into the GWorld
  559.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  560.         if(err) goto bail;
  561.  
  562.         // compress the GWorld containing the image painted on white
  563.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwImage), nil, 0, data, &dataSize, &similarity, nil );
  564.         if ( err ) goto bail;
  565.         
  566.         // At this point, data points to the image data for just the image, newly compressed. Also, hit testing data is contained
  567.         // in the image data if it was specified.
  568.     }
  569.     
  570.     CDSequenceEnd( seq );
  571.     seq = 0;
  572.     
  573.     // free the GWorlds and drop references so we have more memory for PtrToHand
  574.     if( gwImage )    DisposeGWorld( gwImage );
  575.     gwImage = nil;
  576.     if( gwMap )    DisposeGWorld( gwMap );
  577.     gwMap = nil;
  578.     if( gwPrev ) DisposeGWorld( gwPrev );
  579.     gwPrev = nil;
  580.     
  581.     err = PtrToHand( data, imageData, dataSize );
  582.     if ( err ) goto bail;
  583.     
  584.     *idh = desc;
  585.     desc = nil;                // forget about this name for ImageDescriptionHandle so dispose below doesn't catch it
  586.     
  587. bail:
  588.     // tell callback to dispose of anything it allocated. We pass 'err ' in portType if an error occurred
  589.     drawProc( kRecoProcDisposeMsg, nil, nil, err ? FOUR_CHAR_CODE('err ') : 0, drawProcRefcon );
  590.     
  591.     CDSequenceEnd( seq );
  592.     SetGWorld( savePort, saveDevice );
  593.     
  594.     if(gwImage)        DisposeGWorld( gwImage );
  595.     if(gwMap )        DisposeGWorld( gwMap );
  596.     if(gwPrev )        DisposeGWorld( gwPrev );
  597.     if(desc)         DisposeHandle((Handle) desc );
  598.     if(gwMapDesc)    DisposeHandle((Handle) gwMapDesc );
  599.     if(data)        DisposePtr( data );
  600.         
  601.     return err;
  602. }
  603.  
  604.  
  605. /*
  606.     myPictureCompressDrawProc
  607.     
  608.     Helper routine to be used with RecompressWithTransparencyFromProc to compress QuickDraw Pictures.
  609.  */
  610.  
  611. static pascal OSErr myPictureCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType drawingImageType, void * refcon )
  612. {
  613. #if TARGET_OS_MAC
  614. #pragma unused(drawingPort)
  615. #endif
  616.     OSErr err = noErr;
  617.     PictureCompressProcData * data = refcon;
  618.     Rect r;
  619.  
  620.     switch( message ) {
  621.         case kRecoProcInitMsg:
  622.             break;
  623.             
  624.         case kRecoProcDisposeMsg:
  625.             break;
  626.             
  627.         case kRecoProcGetBoundsMsg:
  628.             r = (**data->picture).picFrame;
  629.             
  630.             r.left = EndianS16_BtoN(r.left);
  631.             r.top = EndianS16_BtoN(r.top);
  632.             r.bottom = EndianS16_BtoN(r.bottom);
  633.             r.right = EndianS16_BtoN(r.right);
  634.             
  635.             MacOffsetRect(&r, (short)-r.left, (short)-r.top );
  636.             
  637.             *bounds = r;
  638.             break;
  639.             
  640.         case kRecoProcDrawMsg:
  641.             r = (**data->picture).picFrame;
  642.             
  643.             r.left = EndianS16_BtoN(r.left);
  644.             r.top = EndianS16_BtoN(r.top);
  645.             r.bottom = EndianS16_BtoN(r.bottom);
  646.             r.right = EndianS16_BtoN(r.right);
  647.  
  648.             MacOffsetRect( &r, (short)-r.left, (short)-r.top );
  649.  
  650.             if( kRecoProcOriginalImageType == drawingImageType )
  651.                 DrawPictureNoDither( data->picture, &r );
  652.             break;
  653.         default:
  654.             err = -1;
  655.     }
  656.  
  657.     return err;
  658. }    
  659.     
  660.  
  661. /*
  662.     myImageCompressDrawProc
  663.     
  664.     Helper routine to be used with RecompressWithTransparencyFromProc to compress QuickTime compressed image data.
  665.  */
  666. static pascal OSErr myImageCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType drawingImageType, void * refcon )
  667. {
  668. #if TARGET_OS_MAC
  669. #pragma unused(drawingImageType)
  670. #endif
  671.  
  672.     OSErr err = noErr;
  673.     CompressedImageCompressProcData * data = refcon;
  674.     Rect r;
  675.     
  676.     switch( message ) {
  677.     case kRecoProcInitMsg:
  678.         break;
  679.     case kRecoProcDisposeMsg:
  680.         break;
  681.     case kRecoProcGetBoundsMsg:
  682.         r.left = r.top = 0;
  683.         r.right = (**data->imageDesc).width;
  684.         r.bottom = (**data->imageDesc).height;
  685.         
  686.         *bounds = r;
  687.         break;
  688.     case kRecoProcDrawMsg:
  689.         {
  690.             SignedByte saveState;
  691.             
  692.             r.left = r.top = 0;
  693.             r.right = (**data->imageDesc).width;
  694.             r.bottom = (**data->imageDesc).height;
  695.             
  696.             saveState = HGetState( data->imageData );
  697.             HLockHi( data->imageData );
  698.             
  699.             if( kRecoProcOriginalImageType == drawingImageType )
  700.                 err = DecompressImage( *data->imageData, data->imageDesc, GetGWorldPixMap(drawingPort), &r, &r, srcCopy, nil );
  701.             
  702.             HSetState( data->imageData, saveState );
  703.         }
  704.         break;
  705.     default:
  706.         err = -1;
  707.     }
  708.  
  709.     return err;
  710. }    
  711.  
  712.  
  713.  
  714. /*
  715.     RecompressCompressedImageWithTransparency
  716.     
  717.     Given an ImageDescriptionHandle and a handle to image data, generate new RLE compressed data
  718.     with optional hitTesting and transparency.
  719.  */
  720. OSErr RecompressCompressedImageWithTransparency( ImageDescriptionHandle originalDesc, Handle originalImageData,
  721.                                         RGBColor *keyColor, 
  722.                                         RgnHandle hitTestRegion,
  723.                                         ImageDescriptionHandle *idh, Handle * imageData )
  724. {
  725.     OSErr err = noErr;
  726.     CompressedImageCompressProcData params;
  727.     
  728.     params.imageDesc = originalDesc;
  729.     params.imageData = originalImageData;
  730.     
  731.     err = RecompressWithTransparencyFromProc( myImageCompressDrawProc, ¶ms, 
  732.                                         (Boolean)(hitTestRegion != nil), 
  733.                                         keyColor, 
  734.                                         hitTestRegion, 
  735.                                         idh, imageData );
  736.     
  737.     return err;
  738. }
  739.  
  740. /*
  741.     RecompressPictureWithTransparency
  742.     
  743.     Given a QuickDraw PicHandle, generate new RLE compressed data with optional hitTesting and transparency.
  744.  */
  745. OSErr RecompressPictureWithTransparency( PicHandle originalPicture,
  746.                                         RGBColor *keyColor, 
  747.                                         RgnHandle hitTestRegion,
  748.                                         ImageDescriptionHandle *idh, Handle * imageData )
  749. {
  750.     OSErr err = noErr;
  751.     PictureCompressProcData params;
  752.     
  753.     params.picture = originalPicture;
  754.     
  755.     err = RecompressWithTransparencyFromProc( myPictureCompressDrawProc,
  756.                                             ¶ms, 
  757.                                             (Boolean)(hitTestRegion != nil), 
  758.                                             keyColor, 
  759.                                             hitTestRegion, 
  760.                                             idh,
  761.                                             imageData );
  762.     
  763.     return err;
  764. }
  765.  
  766. /*
  767.     RecompressPictureFileWithTransparency
  768.     
  769.     Given a QuickDraw PICT file, generate new RLE compressed data with optional hitTesting and transparency.
  770.     This function uses GetCompressedImageFromPicture to do the actual work on the PicHandle retrieved from
  771.     the PICT file.
  772.  */
  773. OSErr RecompressPictureFileWithTransparency( FSSpec * spec, 
  774.                                         RGBColor *keyColor, 
  775.                                         RgnHandle hitTestRegion,
  776.                                         ImageDescriptionHandle *idh, Handle * imageData )
  777. {
  778.     OSErr         err = noErr;
  779.     short        sourceRefNum = 0;
  780.     PicHandle    picture = nil;
  781.     long        eof;
  782.     long        countBytes;
  783.     
  784.     *idh = nil;
  785.     *imageData = nil;    
  786.     
  787.     BailOSErr(FSpOpenDF( spec, fsRdPerm, &sourceRefNum ));
  788.     
  789.     BailOSErr(GetEOF( sourceRefNum, &eof ));
  790.     eof -= 512;
  791.     
  792.     BailOSErr(SetFPos( sourceRefNum, fsFromStart, 512 ));
  793.             
  794.     picture = (PicHandle) NewHandle(eof);
  795.     err = MemError();
  796.     BailOSErr(err);
  797.  
  798.     countBytes = eof;
  799.     HLock((Handle) picture);
  800.     BailOSErr( FSRead( sourceRefNum, &countBytes, *picture) );
  801.     HUnlock((Handle) picture);
  802.     
  803.     BailOSErr( RecompressPictureWithTransparency( picture,  keyColor, hitTestRegion,
  804.                                 idh, imageData ));
  805.                                 
  806. bail:
  807.     if ( picture )            DisposeHandle((Handle) picture );
  808.     if ( sourceRefNum )        FSClose( sourceRefNum );
  809.         
  810.     return err;
  811. }
  812.  
  813.